<?php namespace Summer\Hjd\Models;

use Model;
use RainLab\User\Models\User as UserModel;
/**
 * Model
 */
class CurrencyModel extends Model
{
    use \Winter\Storm\Database\Traits\Validation;
    

    /**
     * @var string The database table used by the model.
     */
    public $table = 'summer_hjd_currency';

    /**
     * @var array Validation rules
     */
    public $rules = [
        'slug' => 'required|between:2,255|unique:summer_hjd_currency',
        'title' => 'required|between:2,255',
    ];
    public $hasMany = [
        'currency_rgs' => ['Summer\Hjd\Models\RgRuleModel', 'key' => 'currency_slug', 'otherKey' => 'slug'],
        'currency_wds' => ['Summer\Hjd\Models\WdRuleModel', 'key' => 'currency_slug', 'otherKey' => 'slug']
    ];
    public function afterSave()
    {
        if($this->status==1){
            $currency_slug=$this->slug;
            $user_list=UserModel::get();
            if($user_list->isNotEmpty()){
                foreach ($user_list as $ulv){
                    $user_wallet=WalletModel::where('user_id',$ulv->id)->where('currency_slug',$this->slug)->first();
                    if(!$user_wallet){
                        WalletModel::create([
                            'user_id'=>$ulv->id,
                            'currency_slug'=>$currency_slug,
                            'balance'=>0,
                            'status'=>1,
                        ]);
                    }
                }
            }
        }
    }

    /**
     * 可充值币种-充值记录筛选
     * @return mixed
     */
    public function getFilterRgCurrencyOptions()
    {
        return CurrencyModel::where('status',1)
            ->whereHas('currency_rgs',function ($q){
                $q->where('status',1);
            })
            ->lists('title', 'slug');
    }
    /**
     * 可提现币种-提现记录筛选
     * @return mixed
     */
    public function getFilterWdCurrencyOptions()
    {
        return CurrencyModel::where('status',1)
            ->whereHas('currency_wds',function ($q){
                $q->where('status',1);
            })
            ->lists('title', 'slug');
    }

}
